<template>
	<view class="layout">
		<view class="layout-header">
			<image src="https://dyfxmp-pre.lianlianlvyou.com/avatar/original/LL_IMAGE_e419625681a44c6ab5245d1c11be0c73.png" />
		</view>

		<view
			class="layout-main"
			:class="{ isWechat: isPageType }"
		>
			<view class="layout-main-avatar">
				<image src="https://dyfxmp-pre.lianlianlvyou.com/avatar/original/LL_IMAGE_2f5e50dca18e4cf085ba6c39afa82b8b.png" />
			</view>

			<view class="layout-main-name">
				<image src="https://dyfxmp-pre.lianlianlvyou.com/avatar/original/LL_IMAGE_a7e70f7d755c4d05964245009c96f5f9.png" />
			</view>

			<view class="layout-main-footer">
				<button v-if="isPageType" @click="getUserInfo" :loading="isLoading" :disabled="isLoading" :class="{ active: isLoading }">
					微信授权登录
				</button>

				<button
					v-else
					:loading="isLoading"
					:disabled="isLoading"
					:class="{ active: isLoading }"
					open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber"
				>
					手机号授权登录
				</button>
			</view>
		</view>

		<view class="layout-footer">
			登录即代表您同意
			<text @click="openPlatformPrivacyAgreement">《联联探客隐私协议》</text>
		</view>

		<!-- 成功邀请码提示 -->
		<DistributionInvitation v-model="isPopupObject" @clickCallBack="clickCallBack" ref="DistributionInvitation" />
	</view>
</template>

<script>
import { mapGetters } from 'vuex';
import { defaultImageUrl } from '@/utils';
import { getWxUuid, getUserToken } from '@/api/login';
import { loginOut, getSessionKeyExpired, InvitationCodeMistakeHintList } from '@/utils';

import DistributionInvitation from '@/components/distributionInvitation';

export default {
	name: 'CommonMain',

	props: {
		type: {
			type: String,
			default: 'wechat' // wechat 微信授权登录 phone 手机号授权登录
		}
	},

	data() {
		return {
			isLoading: false,

			wxCode: null,
			invalidateCode: '',
			isPopupObject: {}
		};
	},

	computed: {
		...mapGetters(['getToken', 'userInfo']),

		userAvatar() {
			const {
				type,
				userInfo: { headUrl }
			} = this;

			if (type === 'wechat') {
				return require('@/static/logo.png');
			}

			return headUrl;
		},

		isPageType() {
			const { type } = this;

			return type === 'wechat';
		}
	},

	created() {
		if (this.isPageType) {
			this.getWxCode();
		} else {
			getSessionKeyExpired().then((status) => {
				!status && this.getWxCode();
			});
		}
	},

	methods: {
		getUserInfo() {
			const { wxCode, isLoading, invalidateCode } = this;

			if (isLoading) {
				return;
			}

			this.isLoading = true;

			uni.getUserProfile({
				desc: 'weixin',
				success: (res) => {
					const {
						userInfo: { avatarUrl, nickName }
					} = res;

					const formatNickName = nickName?.replace?.(/\s/g, '');
					getWxUuid({
						code: wxCode,
						invalidateCode,

						nickName: formatNickName || '微信用户',
						avatarUrl: avatarUrl || `${defaultImageUrl}logo.png`
					})
						.then((subRes) => {
							const { code, data } = subRes;

							if (code !== 200) {
								return;
							}

							/**
							 * userInvitationCodeResp: {
							 * 	codeUseStatus 邀请码使用提示：-1邀请码不存在；0可以使用；1使用成功；2已失效；3请勿重复使用邀请码；4已达使用上限
							 *  cycleType 福利周期：1每日；2每周；3每月；4每季度；5每年；9一次性；
							 *  download 邀请码使用成功后的下载次数
							 * }
							 */

							const { userInvitationCodeResp, ...otherParams } = data || {};

							if (!invalidateCode) {
								loginOut(otherParams);
								return;
							}

							if (![0, 1].includes(userInvitationCodeResp.codeUseStatus)) {
								const { hint } = InvitationCodeMistakeHintList.find(
									(item) => item.type === userInvitationCodeResp.codeUseStatus
								);

								uni.showToast({
									mask: true,
									icon: 'none',
									title: hint,
									success: () => {
										setTimeout((e) => {
											loginOut(otherParams);
										}, 1000);
									}
								});
								return;
							}

							this.isPopupObject = {
								...otherParams,
								...userInvitationCodeResp
							};

							// this.$nextTick((e) => {
							// 	!this.$refs.DistributionInvitation.isPopup && loginOut(otherParams);
							// });
						})
						.catch((e) => {
							this.getWxCode();
						})
						.finally((e) => {
							this.isLoading = false;
						});
				},
				fail: () => {
					this.isLoading = false;
				}
			});
		},

		getWxCode() {
			uni.login({
				provider: 'weixin',
				success: (res) => {
					this.wxCode = res.code;
				}
			});
		},

		getPhoneNumber(params) {
			const {
				detail: { encryptedData, iv }
			} = params;
			const {
				getToken,
				userInfo: { nickName, headUrl }
			} = this;

			if (!encryptedData || !iv || this.isLoading) {
				return;
			}

			this.isLoading = true;

			const formatNickName = nickName?.replace?.(/\s/g, '');

			getUserToken({
				iv,

				nickName: formatNickName || '微信用户',
				headerUrl: headUrl || `${defaultImageUrl}logo.png`,

				encryptedData,
				token: getToken
			})
				.then((res) => {
					const { code, data } = res;

					if (code !== 200) {
						return;
					}

					loginOut(data || {});
				})

				.finally(() => {
					this.isLoading = false;
				});
		},

		openComeBack() {
			/* eslint-disable */
			const routes = getCurrentPages();
			const { route } = routes[routes.length - 1] || {};
			const curPage = 'authorizePage/WechatAuthorize'
			/* eslint enable */
			const backPages =[]
			if (curPage === route) {
				uni.switchTab({
						url: '/pages/tabBar/Index'
					});
			}else{
				uni.navigateBack({
					delta: 1
				});
			}
		},

		openPlatformPrivacyAgreement() {
			const webView = `${defaultImageUrl}webView/PlatformPrivacyAgreement.html`;
			const url = `/tandianPage/CommonWebView?webView=${webView}`;

			uni.navigateTo({
				url
			});
		},

		clickCallBack(params) {
			loginOut(params);
		}
	},

	components: {
		DistributionInvitation
	}
};
</script>

<style lang="scss" scoped>
@import '@/style/common.scss';

.layout {
	height: 100vh;
	background: #fff;
	image {
		width: 100%;
		height: 100%;
	}
	&-header {
		height: 480rpx;
	}

	&-main {
		width: calc(100% - 80rpx);
		margin: -180rpx auto 40rpx;
		&-avatar {
			width: 200rpx;
			height: 200rpx;
			margin: -68rpx auto 20rpx;
		}

		&-name {
			width: 328rpx;
			height: 84rpx;
			margin: 0 auto;
		}

		&-footer {
			margin-top: 260rpx;
			button{
				@include Db_newButton();
			}
		}
	}

	&-footer {		
		color: #999;
		text-align: center;
		font-size: 24rpx;
		text {
			color: $themeColor;
		}
	}
}
</style>
